package com.aqiang.lib_core.net

import com.aqiang.lib_core.Config
import com.aqiang.lib_core.net.api.TokenApi
import com.jakewharton.retrofit2.adapter.kotlin.coroutines.CoroutineCallAdapterFactory
import com.zy.core.net.entity.TokenRespEntity
import okhttp3.Interceptor
import okhttp3.OkHttpClient
import okhttp3.logging.HttpLoggingInterceptor
import retrofit2.Retrofit
import retrofit2.converter.gson.GsonConverterFactory
import java.util.concurrent.TimeUnit

object RetrofitManage {
    private val retrofit:Retrofit
    init {
        retrofit = Retrofit.Builder()
            .client(createHttpClient())
            .baseUrl(Config.BASE_URL)
            .addCallAdapterFactory(CoroutineCallAdapterFactory())
            .addConverterFactory(GsonConverterFactory.create())
            .build()
    }

    private fun createHttpClient(): OkHttpClient {
        return OkHttpClient()
            .newBuilder()
            .connectTimeout(10,TimeUnit.SECONDS)
            .readTimeout(10,TimeUnit.SECONDS)
            .writeTimeout(10,TimeUnit.SECONDS)
            .addNetworkInterceptor(createNetworkInterceptor())
            .addInterceptor(createInterceptor())
            .build()
    }

    private fun createInterceptor(): Interceptor {
        val interceptor = Interceptor {
            chain ->
            val request = chain.request()
            val response = chain.proceed(request)
            if(response.code() == 401){
                var token:TokenRespEntity = createToken()
                if (null==token){
                    NullPointerException("token is null or empty...")
                }
                return@Interceptor chain.proceed(request.newBuilder().addHeader("Authorization","${token?.token_type} ${token?.access_token}")
                    .build())
            }
            response
        }
        return interceptor
    }

    private fun createToken(): TokenRespEntity {
        val tokenApi = create(TokenApi::class.java)
        return tokenApi.getToken("password",Config.AUTH_CODE,"").execute().body()!!
    }

    private fun createNetworkInterceptor(): Interceptor {
        val httpLoggingInterceptor = HttpLoggingInterceptor()
        httpLoggingInterceptor.level = HttpLoggingInterceptor.Level.BODY
        return httpLoggingInterceptor
    }

    fun <T> create(clazz: Class<T>):T{
        return retrofit.create(clazz)
    }
}